package com.wjh.service.impl;

import com.wjh.common.CommonMethods;
import com.wjh.common.Constants;
import com.wjh.util.SnowFlakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wjh.common.BaseInfo;
import com.wjh.goods.entity.GoodsEntity;
import com.wjh.mapper.IGoodsMapper;
import com.wjh.goods.request.SaveGoodsRequest;
import com.wjh.service.IGoodsService;
import com.wjh.util.JsonUtils;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 商品Service实现类
 * 
 * @author wenjianhai
 * @date 2023/6/21
 * @since JDK 17
 */
@Slf4j
@Service
public class GoodsServiceImpl implements IGoodsService {

	@Autowired
	private IGoodsMapper goodsMapper;

	/** 雪花算法 */
	@Autowired
	private SnowFlakeIdWorker snowFlakeIdWorker;

	@Override
	public void save(SaveGoodsRequest request, BaseInfo baseInfo) {

		GoodsEntity goods = JsonUtils.parse(JsonUtils.toJSONBytes(request), GoodsEntity.class);
		goods.setPrice(CommonMethods.yuanToFen(request.getPrice()));
		goods.setSellPrice(CommonMethods.yuanToFen(request.getSellPrice()));
		goods.setUpdaterCode(baseInfo.getUserCode());
		goods.setUpdaterName(baseInfo.getUserName());

		// 根据商品名查询商品信息
		GoodsEntity exist = goodsMapper.queryByName(request.getGoodsName());

		if (request.getId() == null || request.getId().intValue() == Constants.NUM_ZERO) {
			/* 新增 */
			if (exist != null) {
				log.error("新增商品信息,商品名称已存在.商品名称:{}", request.getGoodsName());
				throw new RuntimeException("商品名称已存在");
			}
			goods.setGoodsGuid(CommonMethods.getMeUUID());
			goods.setGoodsCode(this.generateCode());
			goods.setCreatorCode(baseInfo.getUserCode());
			goods.setCreatorName(baseInfo.getUserName());

			goodsMapper.save(goods);
		} else {
			/* 修改 */
			if (exist != null && !request.getId().equals(exist.getId())) {
				log.error("修改商品信息,商品名称已存在.商品名称:{}", request.getGoodsName());
				throw new RuntimeException("商品名称已存在");
			}
			goodsMapper.update(goods);
		}
	}

	@Override
	public List<GoodsEntity> queryAll() {
		return goodsMapper.queryAll();
	}

	@Override
	public GoodsEntity queryById(Long id) {
		return id == null ? null : goodsMapper.queryById(id);
	}

	@Override
	public GoodsEntity queryByGuid(String goodsGuid) {
		return StringUtils.isBlank(goodsGuid) ? null : goodsMapper.queryByGuid(goodsGuid);
	}

	private String generateCode() {
		String code = CommonMethods.getNumber(10);
		// 用户编码是否已存在
		Integer count = goodsMapper.isCodeExist(code);

		if (count != null && count.intValue() > Constants.NUM_ZERO) {
			// 编码已存在,继续生成
			code = generateCode();
		}
		return code;
	}
}
